package lm.concurrency.day6.unsafe;

import lm.concurrency.day5.CAS.Account;
import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @Auther: Min.Liu
 * @Description:
 * @Date: Created in 19:13 2024/11/7
 */
public class UnsafeDemo {
    public static void main(String[] args) throws NoSuchFieldException {
        Demo1();
//        Account.demo(new Account() {
//            AtomicData atomicData = new AtomicData(10000);
//            @Override
//            public Integer getBalance() {
//                return atomicData.getData();
//            }
//            @Override
//            public void withdraw(Integer amount) {
//                atomicData.decrease(amount);
//            }
//        });
    }


    //Unsafe的CAS基本使用
    private static void Demo1() throws NoSuchFieldException {
        Unsafe unsafe = UnsafeAccessor.getUnsafe();
        Field id = Student.class.getDeclaredField("id");
        Field name = Student.class.getDeclaredField("name");
        // 获得成员变量的偏移量
        long idOffset = unsafe.objectFieldOffset(id);
        long nameOffset = unsafe.objectFieldOffset(name);
        Student student = new Student();
        // 使用 cas 方法替换成员变量的值
        unsafe.compareAndSwapInt(student, idOffset, 0, 20); // 返回 true
        unsafe.compareAndSwapObject(student, nameOffset, null, "张三"); // 返回 true
        System.out.println(student);
    }
}
